export class HttpError extends Error {
    /**
     * 创建标准化HTTP错误
     * @param {number} statusCode - HTTP状态码
     * @param {string} message - 错误描述
     * @param {Array} details - 错误详情（可选）
     */
    constructor(statusCode, message, details = []) {
      super(message);
      
      // 参数校验
      if (typeof statusCode !== 'number') {
        throw new TypeError('statusCode must be a number');
      }
      if (typeof message !== 'string') {
        throw new TypeError('message must be a string');
      }
  
      this.name = this.constructor.name;
      this.statusCode = statusCode;
      this.expose = statusCode < 500; // 是否向客户端暴露错误详情
      this.details = details;
      this.timestamp = new Date().toISOString();
  
      // 保持错误堆栈
      if (Error.captureStackTrace) {
        Error.captureStackTrace(this, this.constructor);
      }
    }
  
    /**
     * 转换为JSON格式
     * @returns {Object} 可序列化的错误对象
     */
    toJSON() {
      return {
        code: this.statusCode,
        message: this.message,
        ...(this.details.length > 0 && { errors: this.details }),
        timestamp: this.timestamp
      };
    }
  }
  
  export class ValidationError extends HttpError {
    /**
     * 创建数据验证错误
     * @param {Array|Object} errors - 字段级错误信息
     */
    constructor(errors) {
      super(400, 'Validation failed');
      
      // 统一错误结构
      this.details = Array.isArray(errors) 
        ? errors 
        : Object.entries(errors).map(([field, error]) => ({
            field,
            message: error.message,
            ...(error.value && { rejectedValue: error.value })
          }));
    }
  }
  
//   认证/鉴权错误
  export class AuthenticationError extends HttpError {
    constructor(message = 'Authentication required') {
      super(401, message);
    }
  }
//   认证/鉴权错误
  export class AuthorizationError extends HttpError {
    constructor(message = 'Permission denied') {
      super(403, message);
    }
  }
//   请求过多
  export class RateLimitError extends HttpError {
    constructor(retryAfter) {
      super(429, 'Too many requests');
      this.retryAfter = retryAfter;
    }
    
  
    toJSON() {
      return {
        ...super.toJSON(),
        ...(this.retryAfter && { retryAfter: this.retryAfter })
      };
    }
  }
  // 自定义业务错误
export class PaymentRequiredError extends HttpError {
    constructor() {
      super(402, 'Payment required');
      this.details = [{ method: 'credit_card' }];
    }
  }